/*
 *	webcamProcessor.h
 *
 *
 *	created by Jian-Wei Gan, Jason Hsu, and Weiping Zhang
 *	adapted for use with Pixels
 *	formerly imageprocessor.h
 */

#ifndef WEBCAM_PROCESSOR_H
#define WEBCAM_PROCESSOR_H

#include <set>
#include "cglx.h"
#include "webcam.h"

#define IMAGES_LOCATION "stitched"
#define MAX_FRAMES 96
#define NOISE_THRESHOLD 90
#define TIME_TO_WAIT 0.3

class WebcamProcessor 
{
private:
	WebCam* myWebcam;		//overhead camera image information
	GLuint myWidth;			//width of camera image
	GLuint myHeight;		//height of camera image
	GLuint myDepth;			//original aspect ratio(?) of camera image
	GLfloat myElapsedTime;	// time elapsed between camera images
	set<Point3*>* blobCoordinates;	//coordinates that make up a blob

public:
	WebcamProcessor()
	{
		myWebcam = new WebCam(IMAGES_LOCATION, MAX_FRAMES);
		myWidth = myWebcam->getBackground().getImageWidth();
		myHeight = myWebcam->getBackground().getImageHeight();
		myDepth = myWebcam->getBackground().getImageDepth();
		myWebcam->nextFrame();
		myElapsedTime = 0;
		blobCoordinates = new set<Point3*>();
	}

	~WebcamProcessor() 
	{
		delete myWebcam;
	}

	/*
	 * Finds the coordinates of "blobs" present in the webcam image. The coordinates
	 * are screen coordinates, not world coordinates. Translation between the two
	 * occurs in scene.h.
	 */
	set<Point3*>* findBlobs()
	{
		Texture current = myWebcam->getCurrentFrame();
		Texture background = myWebcam->getBackground();	//maybe should be previous frame instead, to track movement not presence
		GLubyte* rawData = current.getImageData();
		GLubyte* bgData = background.getImageData();
		
		if(!blobCoordinates->empty())
		{
			blobCoordinates->clear();
		}
		
		for(GLuint h = 0; h<myHeight; h++)
		{
			for(GLuint w = 0; w<myWidth; w++)
			{
				GLuint index = (h*myWidth + w)*myDepth;
				GLint rdiff = GLint(rawData[index]) - GLint(bgData[index]);
				GLint gdiff = GLint(rawData[index+1]) - GLint(bgData[index+1]);
				GLint bdiff = GLint(rawData[index+2]) - GLint(bgData[index+2]);
				if(abs(rdiff) > NOISE_THRESHOLD || abs(gdiff) > NOISE_THRESHOLD || abs(bdiff) > NOISE_THRESHOLD)
				{
					blobCoordinates->insert(new Point3(w, h, 0));
				}
			}
		}
		myWebcam->nextFrame();
		return blobCoordinates;
	}
};

#endif
